package com.gj.demojuc.chap02;

import java.util.concurrent.TimeUnit;

/**
 * @author gengjian
 * @date 2025/01/21 11:02:39
 * 复习死锁 两个线程 两个锁
 */
public class DeadLockDemo {
    private static final Object lock1 = new Object();
    private static final Object lock2 = new Object();

    public static void main(String[] args) {

        new Thread(()->{
            synchronized (lock1){
                System.out.println(Thread.currentThread().getName() + "获得锁1执行任务");
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "等待抢锁2");
                synchronized (lock2){
                    System.out.println(Thread.currentThread().getName() + "获得锁2执行任务");
                }
            }
        },"线程1").start();

        new Thread(()->{
            synchronized (lock2){
                System.out.println(Thread.currentThread().getName() + "获得锁2执行任务");
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "等待抢锁2");
                synchronized (lock1){
                    System.out.println(Thread.currentThread().getName() + "获得锁1执行任务");
                }
            }
        },"线程2").start();
    }
}
